/**
 * 
 */
package org.jackysoft.util;

import java.io.IOException;
import java.io.StringWriter;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletInputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;

/**
 * @author qujiakang
 * 
 */

public final class ActionUtils {
	static final Log log = LogFactory.getLog(ActionUtils.class);

	/**
	 * @param request
	 *            ServletRequest
	 * @return byte[] 请求输入流中的数据
	 */
	public static Map<String, byte[]> getUploadedContent(
			ServletInputStream input) {
		Map<String, byte[]> cmap = new HashMap<String, byte[]>();
		byte[] cnt = new byte[0];
		try {
			DocumentBuilderFactory factory = DocumentBuilderFactory
					.newInstance();
			DocumentBuilder builder = factory.newDocumentBuilder();
			org.w3c.dom.Document doc = builder.parse(input);
			org.w3c.dom.Element root = doc.getDocumentElement();
			Node xml_File1 = root.getFirstChild();
			NamedNodeMap attList = xml_File1.getAttributes();
			String fileN = "";
			String fileExt = "";
			for (int i = 0; i < attList.getLength(); i++) {
				Node currentNode = attList.item(i);
				if (currentNode.getNodeName().equals("FileName")) {
					fileN = currentNode.getNodeValue();
					fileExt = fileN.substring(fileN.length() - 3);
					fileExt = fileExt.toLowerCase();
					break;
				}
			}
			if ((fileExt.equals("doc")) || (fileExt.equals("xls"))
					|| (fileExt.equals("ppt"))) {
				Node textNode = xml_File1.getFirstChild();
				// BASE64Decoder de = new BASE64Decoder();
				// de.decodeBuffer(textNode.getNodeValue());
				// 下面的字节数组b就是SOAOffice控件提交到服务器的文档流。开发者可编程将b存入数据库字段里，
				// 或作其他任何处理。这是SOAOffice专门为开发者提供的灵活性。
				cnt = EncodeUtils.base64Decode(textNode.getNodeValue());
				cmap.put(fileN, cnt);
			} else {
				log.error(new RuntimeException("类型错误"));
			}
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return cmap;
	}

	/**
	 * @param request
	 *            ServletRequest
	 * @return String 请求输入流中的数据
	 */
	public static String getUploadedDomFilename(ServletInputStream input) {
		String fileN = "";
		String fileExt = "";
		try {
			DocumentBuilderFactory factory = DocumentBuilderFactory
					.newInstance();
			DocumentBuilder builder = factory.newDocumentBuilder();
			org.w3c.dom.Document doc = builder.parse(input);
			org.w3c.dom.Element root = doc.getDocumentElement();
			Node xml_File1 = root.getFirstChild();
			NamedNodeMap attList = xml_File1.getAttributes();

			for (int i = 0; i < attList.getLength(); i++) {
				Node currentNode = attList.item(i);
				if (currentNode.getNodeName().equals("FileName")) {
					fileN = currentNode.getNodeValue();
					fileExt = fileN.substring(fileN.length() - 3);
					fileExt = fileExt.toLowerCase();
					break;
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return fileN;
	}

	/**
	 * @param params
	 *            string-string[] 类型的参数映射
	 * @param name
	 *            要获取的参数名称
	 * @return string 返回参数值
	 */
	public static String parseParameter(Map params, String name) {
		String[] pvalues = (String[]) params.get(name);
		if (pvalues == null)
			return null;
		else if (pvalues.length == 0)
			return null;
		return pvalues[0];
	}

	public static String translateListToXML(List list) {
		StringWriter xml = new StringWriter();
		Document document = DocumentHelper.createDocument();
		Element root = document.addElement("List");
		// String objName="";
		for (Object obj : list) {
			// objName = obj.getClass().getSimpleName();
			// 添加一个对象元素
			Element object = root.addElement("userext");
			Field[] fields = obj.getClass().getDeclaredFields();
			for (Field f : fields) {
				try {
					// 获得获取该属性的方法对象
					Method m = obj.getClass().getMethod(
							"get" + StringUtils.upperFirstChar(f.getName()),
							null);
					// log.info("方法名 : "+m.getName());
					// log.info("类型名 : "+f.getType()+" 类型
					// :"+f.getType().isPrimitive());
					Object value = m.invoke(obj, null);
					// 给对象元素添加属性名为标签名的元素

					if (!f.getType().isInterface()) {
						object.addElement(f.getName()).addAttribute("value",
								value.toString());

					}

				} catch (SecurityException e) {

					e.printStackTrace();
				} catch (NoSuchMethodException e) {

					e.printStackTrace();
				} catch (IllegalArgumentException e) {

					e.printStackTrace();
				} catch (IllegalAccessException e) {

					e.printStackTrace();
				} catch (InvocationTargetException e) {

					e.printStackTrace();
				}
			}// end of for loop inner

		}// end of for loop outer
		OutputFormat format = OutputFormat.createPrettyPrint();
		XMLWriter xw = new XMLWriter(xml, format);
		try {
			xw.write(document);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return xml.toString();
	}
}
